﻿using Shop.Collect;
using Shop.LocalEvent;
using Shop.Model.DB;
using Shop.RemoteModel.Coupon.Model;
using Shop.Service.Interface;
using WeDonekRpc.Client;
using WeDonekRpc.Helper;
using WeDonekRpc.Model;

namespace Shop.Service.lmpl
{
    internal class CouponService : ICouponService
    {
        private readonly ICouponCollect _Service;
        private readonly IUserGradeCollect _UserGrade;
        public CouponService (ICouponCollect service, IUserGradeCollect userGrade)
        {
            this._UserGrade = userGrade;
            this._Service = service;
        }

        public long Add (CouponSet data)
        {
            return this._Service.Add(data);
        }

        public void Delete (long id)
        {
            DBShopCoupon coupon = this._Service.Get(id);
            this._Service.Delete(coupon);
            new CouponEvent(coupon).AsyncPublic("Delete");
        }

        public bool Enable (long id)
        {
            DBShopCoupon coupon = this._Service.Get(id);
            if (this._Service.Enable(coupon))
            {
                new CouponEvent(coupon).AsyncPublic("Enable");
                return true;
            }
            return false;
        }

        public CouponDto Get (long id)
        {
            DBShopCoupon coupon = this._Service.Get(id);
            CouponDto dto = coupon.ConvertMap<DBShopCoupon, CouponDto>();
            if (dto.GradeId.HasValue)
            {
                dto.GradeName = this._UserGrade.GetName(dto.GradeId.Value);
            }
            return dto;
        }

        public bool Offshelf (long id)
        {
            DBShopCoupon coupon = this._Service.Get(id);
            return this._Service.Offshelf(coupon);
        }

        public PagingResult<CouponDatum> Query (CouponQueryParam query, IBasicPage paging)
        {
            CouponDto[] list = this._Service.Query<CouponDto>(query, paging, out int count);
            if (list.IsNull())
            {
                return new PagingResult<CouponDatum>();
            }
            CouponDatum[] dtos = list.ConvertMap<CouponDto, CouponDatum>();
            Dictionary<long, string> grades = this._UserGrade.GetName(list.Where(c => c.GradeId.HasValue).Select(c => c.GradeId.Value).Distinct().ToArray());
            dtos.ForEach(c =>
            {
                if (c.GradeId.HasValue)
                {
                    c.GradeName = grades.GetValueOrDefault(c.GradeId.Value);
                }
            });
            return new PagingResult<CouponDatum>(dtos, count);
        }

        public bool Set (long id, CouponSet data)
        {
            DBShopCoupon coupon = this._Service.Get(id);
            return this._Service.Set(coupon, data);
        }

        public bool Stop (long id)
        {
            DBShopCoupon coupon = this._Service.Get(id);
            return this._Service.Stop(coupon);
        }
    }
}
